#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(QString("复刻键盘"));  // 设置窗口标题栏显示的文字
    QTinit();// 修改QT默认设置

    // 初始化线程
    initThread();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::QTinit()
{
    setFocusPolicy(Qt::StrongFocus);// Qt 框架中用于设置控件（如按钮、文本框等）焦点策略
}

void MainWindow::initConnections()
{
    timer = new QTimer(this);   //主键盘数据轮询定时器  // 父对象

}


void MainWindow::initThread()
{
    //接收键盘数据线程
    usbKeyboard = new UsbKeyboardThread();
    keyboardThread = new QThread();
    usbKeyboard->moveToThread(keyboardThread);
    connect(keyboardThread, &QThread::started, usbKeyboard,&UsbKeyboardThread::init);
    connect(usbKeyboard,&UsbKeyboardThread::KBdataReceived,this,&MainWindow::onKBdataReceived);
    connect(usbKeyboard,&UsbKeyboardThread::dataReceived, this, &MainWindow::onDataReceived);
    connect(usbKeyboard,&UsbKeyboardThread::TPdataReceived, this, &MainWindow::onTPdataReceived);
    connect(usbKeyboard,&UsbKeyboardThread::KTdataReceived, this, &MainWindow::onKTdataReceived);
    connect(this, &MainWindow::destroyed,[this](){
        usbKeyboard->stop();
        keyboardThread->quit();  // 退出线程
        keyboardThread->wait();  // 等待线程结束
        delete keyboardThread;
        delete usbKeyboard;});
    keyboardThread->start();//开启线程
}

void MainWindow::onKBdataReceived(const QByteArray &receivedKeydata)
{

}

void MainWindow::onDataReceived(const QByteArray &receivedKeydata)
{

}

void MainWindow::onTPdataReceived(const QByteArray &receivedKeydata)
{

}

void MainWindow::onKTdataReceived(const QByteArray &receivedKeydata)
{

}

// 更新连接状态显示
void MainWindow::updateConnectionStatus(bool isConnected)
{
    if (isConnected) {
        ui->label->setText("已连接");
        ui->label->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(0, 0, 0);");
    } else {
        ui->label->setText("未连接");
        ui->label->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);");
    }
}

void MainWindow::on_connect_keyboard_clicked()
{
    qDebug() << "尝试连接键盘设备...";

    // 检查线程状态，如果线程未启动则启动
    if (!keyboardThread->isRunning()) {
        keyboardThread->start();
    }

    // 尝试重新连接设备
    usbKeyboard->perform(RECONNECT_KBDEVICE);

    // 立即检查连接状态并更新显示
    bool isConnected = usbKeyboard->getKBConnectStatus();
    updateConnectionStatus(isConnected);

    qDebug() << "连接状态:" << (isConnected ? "已连接" : "未连接");
}

